package ecmnext.gclient.gui;

/***************************************************************/
/*                     SOFTWARE SECTION                        */
/***************************************************************/
/*
 * <p>Name: ECMNext</p>
 * <p>Description: Simulation of the platform of trading Software</p>
 * <p>Licence: General Public License</p>
 * <p>Organisation: EC Marseille</p>
 * <p>Persons involved in the project : groupe Plateforme de Trading</p>
 * <p>Current version: 1.0</p>
 */

/***************************************************************/
/*                       IMPORT SECTION                        */
/***************************************************************/

import javax.swing.*;

import ecmnext.client.*;
import ecmnext.utils.*;
import java.awt.Dimension;

/***************************************************************/
/*               ClientTimer CLASS SECTION                 */
/***************************************************************/
/**
 * <p>Title : ClientTimer</p>
 * <p>Description :</p>
 * @author Xuewen YANG ET Antoine COUDERC
 * @version 1.0
 */

public class ClientTimer extends Thread{

  //private JTextField text;
  private JLabel text;

  public ClientTimer(JLabel field) {
    this.text = field;
  }

  public String getText(){
    return text.getText();
  }
  /**
   *If the experiment and period are on, we display the current number of periods and the time remaining
   * in this period.
   * If exception takes place, we send a warn.
   */
  public void run() {
    while(true) {
      if (ClientCore.getExperimentManager().getExperimentState() == ClientExperimentManager.EXP_ON_PER_ON) {
        text.setText("Period " + (ClientCore.getExperimentManager().getCurrentPeriod() + 1)                     + " - " + this.msecToString(ClientCore.getExperimentManager().getRemainingTimeInPeriod()));
      }
      try {
        this.sleep(250);
      }
      catch (InterruptedException ex) {
        Utils.logger.warn("ServerTimer sleep interrupted. " + ex.toString());
      }
    }
  }
  /**
   * We express the Client time in minute and second.
   * We maintain the double digital form of seconds.
   * @param ms long
   * @return String
   */
  private String msecToString(long ms) {
    int minute = (int)ms / 60000;
    int second = (int)(ms - minute * 60000) / 1000;
    String seconds;

    if(second <10) {
      seconds = "0"+second;
    }
    else {
      seconds = Integer.toString(second);
    }
    return ((minute == 0) ? "" : Integer.toString(minute) + "min ") + seconds + "s";
  }
}
